﻿namespace UnityEngine
{
    public static class CanvasEx
    {
        /// <summary>
        /// 将世界坐标转换到Canvas中的本地坐标
        /// </summary>
        /// <param name="canvas"></param>
        /// <param name="worldCamera"></param>
        /// <param name="worldPosition"></param>
        /// <returns></returns>
        public static Vector2 WorldToLocalPosition(this Canvas canvas, Camera worldCamera, Vector3 worldPosition)
        {
            Vector2 pos;
            RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform, worldCamera.WorldToScreenPoint(worldPosition), canvas.worldCamera, out pos);
            return pos;
        }

        /// <summary>
        /// 将屏幕坐标转换到Canvas中的本地坐标
        /// </summary>
        /// <param name="canvas"></param>
        /// <param name="screenPos"></param>
        /// <returns></returns>
        public static Vector2 ScreenToLocalPosition(this Canvas canvas, Vector3 screenPos)
        {
            Vector2 pos;
            RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform, screenPos, canvas.worldCamera, out pos);
            return pos;
        }
    }
}
